package com.youedata.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.youedata.modular.model.dto.EncryptDTO;
import com.youedata.modular.model.dto.GetUserInfoDTO;
import com.youedata.modular.model.dto.UserInfoByOpenidDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author: hao.yan
 * @date: 17:27
 */
@Slf4j
public class sdkUtil {

    private static final String SUCCESS = "200";
    private static final String GETAUTHCODE_URL = "https://app.myyancheng.com.cn/api/auth/openPlatform/authCode/getAuthCode.do";
    private static final String GETACCESSTOKEN_URL = "https://app.myyancheng.com.cn/api/auth/openPlatform/accessToken/getAccessToken.do";
    private static final String REFRESHACCESSTOKEN_URL = "https://app.myyancheng.com.cn/api/auth/openPlatform/accessToken/refreshAccessToken.do";
    private static final String CHECKACCESSTOKEN_URL = "https://app.myyancheng.com.cn/api/auth/openPlatform/accessToken/checkAccessToken.do";
    private static final String CHECKREQUESTCODE_URL = "https://app.myyancheng.com.cn/api/auth/openPlatform/request/checkRequestCode.do";

    /**
     * 获取initCode
     *
     * @param url    服务地址
     * @param appId  第三方服务在开放平台申请的 appId
     * @param appKey 第三方服务在开放平台申请的 appKey
     */
    public static String getInitCode(String url, String appId, String appKey) {
        // 时间戳（长度为8到15位的时间戳）
        String timestamp = System.currentTimeMillis() + "";
        // 随机序列（长度为10位的数字序列）
        String randomSeries = (new Random().nextInt(9999) + 10000) + "" + (new Random().nextInt(9999) + 10000);

        EncryptDTO encryptDTO = new EncryptDTO();
        encryptDTO.setAppId(appId);
        encryptDTO.setAppKey(appKey);
        encryptDTO.setTimestamp(timestamp);
        encryptDTO.setRandomSeries(randomSeries);

        // 依次将appId:value、appKey:value、randomSeries:value、timestamp:value四个键值对拼接成字符串，然后MD5加密，得到cipherText的值。
        String cipherText = EncryptUtil.encrypt(encryptDTO);

        Map<String, String> params = Maps.newHashMap();
        params.put("appId", appId);
        params.put("timestamp", timestamp);
        params.put("randomSeries", randomSeries);
        params.put("cipherText", cipherText);

        return HttpClientUtil.doPostJson(url, JSON.toJSONString(params));
    }

    /**
     * 获取authCode
     *
     * @param url    服务地址
     * @param appId  第三方服务在开放平台申请的 appId
     * @param appKey 第三方服务在开放平台申请的 appkey
     */
    public static String getAuthCode(String url, String appId, String appKey) {
        // 时间戳（长度为8到15位的时间戳）
        String timestamp = System.currentTimeMillis() + "";
        // 随机序列（长度为10位的数字序列）
        String randomSeries = (new Random().nextInt(9999) + 10000) + "" + (new Random().nextInt(9999) + 10000);

        EncryptDTO encryptDTO = new EncryptDTO();
        encryptDTO.setAppId(appId);
        encryptDTO.setAppKey(appKey);
        encryptDTO.setTimestamp(timestamp);
        encryptDTO.setRandomSeries(randomSeries);

        // 依次将appId:value、appKey:value、randomSeries:value、timestamp:value四个键值对拼接成字符串，然后MD5加密，得到cipherText的值。
        String cipherText = EncryptUtil.encrypt(encryptDTO);

        Map<String, String> params = Maps.newHashMap();
        params.put("appId", appId);
        params.put("timestamp", timestamp);
        params.put("randomSeries", randomSeries);
        params.put("cipherText", cipherText);

        return HttpClientUtil.doPostJson(url, JSON.toJSONString(params));

    }

    /**
     * 获取accessToken
     *
     * @param appId    第三方服务在开放平台申请的 appId
     * @param authCode 获取访问令牌的校验码，由开放平台生成，用于安全性校验
     */
    public static String getAccessToken(String url, String appId, String authCode) {
        Map<String, String> params = Maps.newHashMap();
        params.put("appId", appId);
        params.put("authCode", authCode);

        return HttpClientUtil.doPostJson(url, JSON.toJSONString(params));
    }

    /**
     * 刷新accessToken
     */
    public static void refreshAccessToken() {
        // 第三方服务在开放平台申请的appId
        String appId = "av8eZ4pK81cTQxsO72ZcRR1vMxwaZxc1";
        // getAccessToken() 返回的refreshToken
        String refreshToken = "12b2aafb990f441e877a6fd68b989739";
        Map<String, String> params = new HashMap<String, String>();
        params.put("appId", appId);
        params.put("refreshToken", refreshToken);

        String resultJson = HttpClientUtil.doPostJson(REFRESHACCESSTOKEN_URL, JSON.toJSONString(params));
        if (resultJson != null) {
            Map resultMap = JSON.parseObject(resultJson, Map.class);
            if (SUCCESS.equals(resultMap.get("code"))) {
                System.out.println(resultMap.get("data"));
            } else {
                System.out.println(resultMap.get("msg"));
            }
        }
    }

    /**
     * 校验accessToken
     */
    public static void checkAccessToken() {
        // 第三方服务在开放平台申请的appId
        String appId = "av8eZ4pK81cTQxsO72ZcRR1vMxwaZxc1";
        String accessToken = "e314ffea99484af488352b4357db5038";
        Map<String, String> params = new HashMap<String, String>();
        params.put("appId", appId);
        params.put("accessToken", accessToken);

        String resultJson = HttpClientUtil.doPostJson(CHECKACCESSTOKEN_URL, JSON.toJSONString(params));
        if (resultJson != null) {
            Map resultMap = JSON.parseObject(resultJson, Map.class);
            if (SUCCESS.equals(resultMap.get("code"))) {
                System.out.println(resultMap.get("data"));
            } else {
                System.out.println(resultMap.get("msg"));
            }
        }
    }

    /**
     * 校验requestCode
     *
     * @param url         服务地址
     * @param appId       第三方服务在开放平台申请的 appId
     * @param accessToken 从开放平台获取的应用级别的访问令牌
     * @param requestCode Native 在开放平台申请的 requestCode
     */
    public static String checkRequestCode(String url, String appId, String accessToken, String requestCode) {
        Map<String, String> params = Maps.newHashMap();
        params.put("requestCode", requestCode);
        params.put("accessToken", accessToken);
        params.put("appId", appId);

        return HttpClientUtil.doPostJson(url, JSON.toJSONString(params));
    }

    /**
     * 获取用户信息
     *
     * @param url             服务地址
     * @param userInfoDTO 用户级别的访问令牌
     */
    public static UserInfoByOpenidDTO getUserByUserAccessToken(String url, GetUserInfoDTO userInfoDTO) {
        UserInfoByOpenidDTO userInfoByOpenidDTO = null;
        Map<String, String> params = Maps.newHashMap();
        params.put("appId", userInfoDTO.getAppId());
        params.put("userAccessToken", userInfoDTO.getUserAccessToken());
        try {
            String resultJson = HttpClientUtil.doPostJson(url, JSON.toJSONString(params));
            log.info("response:{}", resultJson);
            if (StringUtils.isEmpty(resultJson)) {
                return null;
            }
            String userInfoJson = JSON.toJSONString(JSONObject.parseObject(resultJson).get("data"));
            if (StringUtils.isEmpty(userInfoJson)) {
                return null;
            }
            userInfoByOpenidDTO = JSONObject.parseObject(userInfoJson, UserInfoByOpenidDTO.class);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("url:{}, param:{}", url, params);
        }

        return userInfoByOpenidDTO;
    }

}
